﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using Caliburn.Micro;

namespace AppReviewerClient
{
    public class LoginViewModel : ViewAware
    {

        private string _tempUsername;
        private string _tempPassword;
        private bool _tempRememberMe;

        private bool _rememberMe;
        public bool RememberMe
        {
            get { return _rememberMe; }
            set
            {
                _rememberMe = value;
                NotifyOfPropertyChange(() => RememberMe);
            }
        }
        private string _username;
        public string Username
        {
            get { return _username; }
            set
            {
                _username = value;
                NotifyOfPropertyChange(() => Username);
            }
        }
        private string _password;
        public string Password
        {
            get { return _password; }
            set
            {
                _password = value;
                NotifyOfPropertyChange(() => Password);
            }
        }

        private string _errorMessage;
        public string ErrorMessage
        {
            get { return _errorMessage; }
            set
            {
                _errorMessage = value;
                NotifyOfPropertyChange(() => ErrorMessage);
            }
        }

        private readonly ShellViewModel _parent;

        public LoginViewModel(ShellViewModel parent)
        {
            _parent = parent;

            try
            {
                var array = FilepathHelper.GetCredentials();
                _tempUsername = Username = array["username"];
                _tempPassword = Password = array["password"];
                CredentialsValid = bool.Parse(array["valid"]);
            }
            catch (Exception)
            {

            }

        }

        public bool? CredentialsValid;

        protected override void OnViewLoaded(object view)
        {
            base.OnViewLoaded(view);

            LoginCmd();
        }

        private bool _isWaiting;
        public bool IsWaiting
        {
            get { return _isWaiting; }
            set
            {
                _isWaiting = value;
                NotifyOfPropertyChange(() => IsWaiting);
            }
        }


        /// <summary>
        /// Prova credenziali
        /// </summary>
        public void LoginCmd()
        {
            if (!CredentialsValid.HasValue || !CredentialsValid.Value)
                if (!(string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password)))
                {
                    IsWaiting = true;

                    using (var webClient = new WebClientEx { Credentials = new NetworkCredential(Username, Password) })
                    {
                        var values = new NameValueCollection
                                     {
                                         {"username", Username},
                                         {"password", Password},
                                     };


                        // Login
                        webClient.UploadValuesCompleted += WebClientUploadValuesCompleted;
                        var url = UrlSiteHelper.GetCheckUser(ShellViewModel.Host);

                        webClient.UploadValuesAsync(new Uri(url), values);
                    }
                }
        }

        void WebClientUploadValuesCompleted(object sender, UploadValuesCompletedEventArgs e)
        {
            IsWaiting = false;
            try
            {
                var json = Encoding.UTF8.GetString(e.Result);

                if (json.ToLower() == "true")
                {
                    CredentialsValid = true;

                    SaveCredentials();

                    ErrorMessage = string.Empty;

                    CloseWindow();

                    _parent.OnLogged();
                }
                else
                {
                    ErrorMessage = "Credenziali errate.. ";
                }
            }
            catch (Exception)
            {

            }
        }

        public void CancelCmd()
        {
            // chiude finestra
            Username = _tempUsername;
            Password = _tempPassword;

            CloseWindow();
        }

        public void CloseWindow()
        {
            (GetView() as Window).Close();

        }

        public void LogOffCmd()
        {
            Username = string.Empty;
            Password = string.Empty;

            CredentialsValid = false;

            SaveCredentials();
        }

        private void SaveCredentials()
        {
            _tempUsername = Username;
            _tempPassword = Password;

            var valid = false;

            if (CredentialsValid.HasValue)
                valid = CredentialsValid.Value;

            FilepathHelper.SaveCredentials(Username, Password, valid);

            _parent.DisplayUsername = Username;
        }

    }
}
